package com.austin.framework.cacheableExtend.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: austin
 * @since: 2023/2/18 21:14
 */
@Slf4j
@Component
public class LockService {

    @Autowired
    private RedisTemplate redisTemplate;

    public boolean grabLock(String key) {
        return grabLock(key, 10, TimeUnit.SECONDS);
    }

    public boolean grabLock(String key, Integer duration, TimeUnit timeUnit) {
        boolean flag = false;
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        long nowTime = System.currentTimeMillis();
        // 尝试nx插入数据
        Boolean result = valueOperations.setIfAbsent(key, String.valueOf(nowTime));
        if (null != result && result) {
            // 设置超时时间
            redisTemplate.expire(key, duration, timeUnit);
            flag = true;
        }
        return flag;
    }

    /**
     * 释放锁
     *
     * @param key
     * @return
     */
    public boolean releaseLock(String key) {
        return redisTemplate.delete(key);
    }
}
